<template>
  <div>
    <el-dialog
      title="上传"
      :visible.sync="show"
      width="30%"
      :close-on-click-modal="false"
      :on-progress="onProgressMethods"
      :before-close="handleClose">
      <div>
        <el-form ref="form" label-width="80px">
          <!-- <el-form-item label="缩略图">
            <template v-if="!image">
              <el-upload
                size="mini"
                style="width: 100%;"
                class="upload-demo"
                drag
                :on-success="uploadImageSuccess"
                :action="uploadUrl"
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              </el-upload>
            </template>
            <div class="upload-file-icon" v-else>
              <div @click="delFileIcon" class="el-icon-circle-close close-file-icon"></div>
              <el-image
                style="width: 100px; height: 100px"
                :src="image"
                fit="cover"></el-image>
            </div>
          </el-form-item> -->

          <el-form-item label="文件">
            <el-upload
              style="width: 100%;"
              class="upload-demo"
              drag
              multiple
              :file-list="fileList"
              :on-success="uploadSuccess"
              :action="uploadUrl"
              :before-upload="beforeAvatarUpload"
              :accept="mediaType == 1 ? videoFormat : mediaType == 2 ? imageFormat : mediaType == 3 ? officeFormat : ''"
              @drop.native="e => beforeUploadFile(e.dataTransfer.files[0])"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            </el-upload>
          </el-form-item>

        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">确 定</el-button>
<!--        <el-button type="primary" @click="confirmUploadFile">确 定</el-button>-->
      </span>
    </el-dialog>

  </div>
</template>

<script>
import * as service from './service'
import {formatMediaType} from "@/utils/config";
export default {
  name: "index",
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    mediaType: {
      type: [Number, String],
      default: ''
    },
    uploadFileType: {
      type: String,
      default: ''
    },
    parentId: {
      type: String,
      default: 0
    }
  },
  data() {
    return {
      imageFormat: ".jpg,.png,.jpeg,.JPG,.PNG,.JPEG",
      videoFormat: ".mp4,.avi,.dat,.dvr,.vcd,.mov,.svcd,.vob,.dvd,.dvtr,.bbc,.evd,.flv,.rmvb,.wmv,.mkv,.3gp,.rmvb",
      officeFormat: ".xlsx,.pdf,.ppt,.pptx,.xls,.doc,.docx,.dotx,.dotm,.ppsx,.pptm,.xps",
      fileList: [],
      uploadUrl: window.ajaxUploadUrl + '/common/fileApi/file',
      uploadList: [],
      image: '',
      tmpList: [],
      isUploadFinish: true
    }
  },
  watch: {
    show(val) {
      if(val) {
        this.fileList = [];
        this.tmpList = [];
      }
    }
  },
  methods: {
    beforeUploadFile(file) {
      var suffix = "."+file.name.substring(file.name.lastIndexOf(".") + 1);
      if(this.mediaType == 1) {
        if(!this.videoFormat.includes(suffix)){
          this.$message.error('文件格式错误')
          return false;
        }
      } else if(this.mediaType == 2) {
        if(!this.imageFormat.includes(suffix)){
          this.$message.error('文件格式错误')
          return false;
        }
      } else if(this.mediaType == 3) {
        if(!this.officeFormat.includes(suffix)){
          this.$message.error('文件格式错误')
          return false;
        }
      }
      return true;
    },
    beforeAvatarUpload() {
      this.isUploadFinish = false
    },
    uploadSuccess(res, file) {
      console.log('res ---', res.data)
      res.data.forEach((item) => {
        item.mediaLink = item.file // 换个字段名
        if(item.fileName.length > 140) {
          item.fileName = item.fileName.slice(0, 140)
        }
        let obj = {
          ...item,
          ...file,
          image: this.image
        }
        this.tmpList.push(obj)
      })

      this.saveFileContent(this.tmpList[this.tmpList.length - 1])
    },
    uploadImageSuccess(res, file) {
      this.image = res.data[0].file
    },
    delFileIcon() {
      this.image = ''
    },
    transformUrlLink(url) {
      let final = url.substring(url.lastIndexOf(".") + 1)
      return final.toLowerCase()
    },
    confirm(){
      this.$emit('on-close')
    },
    handleClose() {
      console.log('isUploadFinish ---', this.isUploadFinish)
      if(!this.isUploadFinish) {
        this.$message.error('上传任务还未完成，请稍后再关闭')
        return
      }
      this.$emit('on-close')
    },
    saveFileContent(row) {
      const demoUrl = row.mediaLink
      const suffix = this.transformUrlLink(demoUrl)
      const params = {
        mediaLink: demoUrl,
        mediaName: row.name.split(".")[0],
        mediaSuffix: suffix,
        size: parseInt((row.size / 1024).toString(), 10),
        mediaType: formatMediaType(suffix),
        fileType: 2,
        image: this.image,
        parentId: this.parentId
      }
      service.saveFileContent(params).then(() => {
        this.$emit('on-confirm', this.uploadList)
        this.image = ''
        this.isUploadFinish = true
      })
    },
    confirmUploadFile() {
      this.$emit('on-confirm', this.uploadList)
    },
    onProgressMethods(event, file, fileList) {
      console.log('event, file, fileList ---', event, file, fileList)
    }
  }
}
</script>

<style scoped>
  .upload-file-icon{
    position: relative;
    width: 100px;
    .close-file-icon{
      position: absolute;
      top: -10px;
      right: -10px;
      font-size: 18px;
      z-index: 1000;
    }
  }
</style>
